import React, { memo, useMemo, useState, useEffect } from 'react';
import { Table, Icon } from 'antd';
import { formatMessage } from 'umi';

import { numberFormat } from '@/utils/formatterUtil';

import OverviewHeader from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/OverviewHeader/index';
import TablePercentWrapper from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/TablePercentWrapper';
import SummaryFoot from '@/components/SummaryTable/SummaryFoot';
import TableStyles from '@/components/SummaryTable/index.less';
import styles from '@/pages/SalaryManage/SalaryCalculate/Recheck/index.less';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';

const DecimalPlacesWrapper = ({ value = 0 }) => numberFormat(value, null);

const DecimalPlacesRateWrapper = ({ value = 0 }) => `上个月实发薪资：${numberFormat(value, null)}元`;

//  固定头部
const tableHeader = [
    {
        // 序号
        title: formatMessage({
            id: 'salaryOverview.table.departmentCode'
        }),
        dataIndex: 'deptCode',
        hidden: true,
        width: 50
    },
    {
        // 部门
        title: () => (
            <>
                <Icon
                    type="caret-down"
                    style={{
                        opacity: 0,
                        marginRight: 5
                    }}
                />
                {formatMessage({
                    id: 'salaryOverview.table.departmentName'
                })}
            </>
        ),
        width: '30%',
        dataIndex: 'deptName',
        render: text => <EmptyPlaceHolder value={text} />
    },
    {
        // 实发薪资
        title: formatMessage({
            id: 'salaryOverview.table.encryptTotalPayAmt'
        }),
        dataIndex: 'payAmt',
        render: (text, record) => (
            <TablePercentWrapper
                name={<DecimalPlacesWrapper value={record.payAmt} />}
                rate={record.payAmtRate}
                type={record.payAmtRateFL}
                title={<DecimalPlacesRateWrapper value={record.lmPayAmt} />}
            />
        ),
        align: 'right',
        defaultSortOrder: 'descend',
        width: '18%',
        sorter: (a, b) => a.payAmt - b.payAmt
    },
    {
        // 税前薪资
        title: formatMessage({
            id: 'salaryOverview.table.encryptTotalTaxAmt'
        }),
        render: text => (
            <span className={salaryStyle.currency}>
                <EmptyPlaceHolder value={numberFormat(text, null)} />
            </span>
        ),
        dataIndex: 'taxAmt',
        align: 'right',
        width: '18%',
        sorter: (a, b) => a.taxAmt - b.taxAmt
    },
    {
        // 部门人数
        title: formatMessage({
            id: 'salaryOverview.table.employeeTotalNum'
        }),
        align: 'right',
        dataIndex: 'em',
        render: (text, record) => (
            <TablePercentWrapper
                name={record.em}
                numberType={false}
                rate={record.emRate}
                type={record.emRateFL}
                title={`上个月部门人数：${record.lmEm}人`}
            />
        ),
        width: '16%',
        sorter: (a, b) => a.em - b.em
    },
    {
        // 平均薪资
        title: formatMessage({
            id: 'salaryOverview.table.encryptAverageAmt'
        }),
        dataIndex: 'deptAvgAmt',
        align: 'right',
        width: null,
        render: text => (
            <span className={salaryStyle.currency}>
                <EmptyPlaceHolder value={numberFormat(text, null)} />
            </span>
        ),
        sorter: (a, b) => a.deptAvgAmt - b.deptAvgAmt
    }
];

const SalaryOverviewWrapper = ({
    period,
    dispatch,
    dispatchType,
    checkButtonList,
    tableLoading,
    dataSource = [],
    footerSource = [],
    searchModel = {},
    organizationList,
    rowKey = 'id'
}) => {
    //  表单展开数组
    const [expandedRowArr, setExpandedRowArr] = useState([]);

    //  表单头部优化
    const renderColumns = useMemo(() => tableHeader.filter(item => !item.hidden), [tableHeader]);

    //  表单全部展开 =》获取展开数组
    const expandCodeFn = list => {
        const arr = [];
        list.forEach(
            item =>
                item.resultVOS &&
                item.resultVOS.length > 0 &&
                arr.push(item.deptCode) &&
                arr.push(...expandCodeFn(item.resultVOS))
        );
        return arr;
    };

    //  展开或收缩事件
    const changeExpand = val => {
        setExpandedRowArr(val ? expandCodeFn(JSON.parse(JSON.stringify(dataSource))) : []);
    };
    //  部门全部展开或合并按钮
    const closeOrOpenWrapper = useMemo(() => {
        if (expandedRowArr && expandedRowArr.length > 0) {
            return <Icon type="caret-down" className={styles.expand} onClick={() => changeExpand(false)} />;
        }

        return (
            <Icon
                type="caret-right"
                className={styles.expand}
                style={{
                    opacity: tableLoading ? 0.5 : 1
                }}
                onClick={() => changeExpand(true)}
            />
        );
    }, [expandedRowArr, tableLoading]);

    useEffect(() => {
        changeExpand(true);
    }, [tableLoading, dataSource]);

    return (
        <>
            <OverviewHeader
                period={period}
                dispatch={dispatch}
                dispatchType={dispatchType}
                checkButtonList={checkButtonList}
                searchModel={searchModel}
                organizationList={organizationList}
            />
            <div
                style={{
                    position: 'relative'
                }}
            >
                {closeOrOpenWrapper}
                <Table
                    columns={renderColumns}
                    rowKey={rowKey}
                    dataSource={dataSource}
                    className={TableStyles.summaryTable}
                    childrenColumnName="resultVOS"
                    expandIcon={item => {
                        if (!item.record.resultVOS || item.record.resultVOS.length === 0) {
                            return (
                                <Icon
                                    type="caret-right"
                                    style={{
                                        opacity: 0,
                                        marginRight: 5
                                    }}
                                />
                            );
                        }
                        if (item.expanded) {
                            return (
                                <Icon
                                    type="caret-down"
                                    onClick={e => {
                                        item.onExpand(item.record, e);
                                    }}
                                    style={{
                                        marginRight: 5
                                    }}
                                />
                            );
                        }
                        return (
                            <Icon
                                type="caret-right"
                                onClick={e => {
                                    item.onExpand(item.record, e);
                                }}
                                style={{
                                    marginRight: 5
                                }}
                            />
                        );
                    }}
                    expandedRowKeys={expandedRowArr}
                    onExpand={(expanded, record) => {
                        if (expanded) {
                            setExpandedRowArr([...expandedRowArr, record.deptCode]);
                        } else {
                            setExpandedRowArr(expandedRowArr.filter(item => !expandCodeFn([record]).includes(item)));
                        }
                    }}
                    footer={() => {
                        if (dataSource && dataSource.length > 0 && footerSource) {
                            return (
                                <SummaryFoot
                                    rowKey={rowKey}
                                    columns={renderColumns}
                                    dataSource={footerSource}
                                    style={{
                                        boxShadow: '0 -4px 12px rgba(0,0,0, 8%)'
                                    }}
                                    scroll={{
                                        x: 'max-content'
                                    }}
                                />
                            );
                        }
                        return null;
                    }}
                    pagination={false}
                    scroll={{
                        x: 'max-content',
                        y: 632
                    }}
                />
            </div>
        </>
    );
};

SalaryOverviewWrapper.displayName = 'SalaryOverviewWrapper';

export default memo(SalaryOverviewWrapper);
